<template>
	<view class="main">
		<form class='loginView' @submit="upload">
			<view class="input-view" v-if="query.type!=='0'">
				<view class="label-view">
					<text class="label">分类</text>
				</view>
				<view class="uni-list-cell-db">
					<picker @change="bindPickerChange" :value="index" range-key="name" :range="tagNameList">
						<view class="uni-input">{{tagNameList[index] && tagNameList[index].name}}</view>
					</picker>
				</view>
			</view>
			<!--图片标题-->
			<view class="input-view" style="margin-top:15px;">
				<view class="label-view">
					<text class="label" style="width: 40px;">标题</text>
				</view>
				<input class="input" type="text" placeholder="请输入图片标题" name="title" v-model="title"/>
			</view>
			<view class="input-view" style="height: 280px;margin-top:15px;">
				<view class="label-view">
					<text class="label">图片</text>
				</view>
				<!-- 图片 -->
				<view @click="changeAvatar">
					<view class="imgflex">
						<image v-for="(item,index) in imgList" :key="index" class="card-img card-list2-img" :src="imgList[index]"></image>
					</view>
				</view>
			</view>
			<view class="button-view">
				<button type="default" class="login" hover-class="hover" formType="submit">确认</button>
			</view>
		</form>
		<image v-if=hasFind :src="imgList[1]" class="findImg"></image>
		<view v-if=hasFind class="cover">
		</view>
		<view  v-if=hasFind class="btnClose" @click="closeCover">
			x
		</view>
	</view>
	
</template>

<script>
	export default {
		data() {
			return {
				imgList: [
					"../../static/upload.png"
				],
				//图片指纹字符串
				fingerprint: '',
				/**
				 * 图片静态地址
				 */
				photoUrl: '',
				//实体路径
				filePath: '',
				//分类信息
				tagList: [],
				//分类id,默认为1
				tagId: 1,
				//picker显示数据
				tagNameList: [],
				//脚标
				index: 0,
				//图片标题
				title:'',
				query:{},
				hasFind: false ,// 是否识别到了图片
				findImgUrl: '' // 识别到的图片返回的url
			}
		},
		onLoad(query) {
			this.query = query //路由参数
			console.log(this.query,'query');
		},
		//初始化执行
		created() {
			this.getTagList()
			if(this.query.type === "0") {
				uni.setNavigationBarTitle({
					title: "以图识图" //这是修改后的导航栏文字
				})
			}
		},
		methods: {
			//上传图片到服务器
			upload(e) { 
				// 创建一个 Date 对象
				const currentDate = new Date();
				// 获取年、月、日
				const currentYear = currentDate.getFullYear();
				const currentMonth = currentDate.getMonth() + 1; // 月份从0开始，需要加1
				const currentDay = currentDate.getDate();
				console.log(`当前日期：${currentYear}-0${currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`);
				console.log('tagNameList', this.tagNameList[this.index])
				if (this.imgList.length ===1) {
				    uni.showToast({
				        title: "请上传图片",
				        icon: "error"
				    })
				    return;
				}
				if (this.title === '') {
				    uni.showToast({
				        title: "请输入标题",
				        icon: "error"
				    })
				    return;
				}
				var that = this
				if(+this.query.type === 0) {
					uni.request({
						url:that.$serverUrl + 'like',
						method:'POST',
						header: {
							'token': uni.getStorageSync('token'),
							'content-type': 'application/json' //自定义请求头信息
						},
						data: {
							//只需传入图片信息与分类id
							dateTime: `${currentYear}-0${currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`,
							userId: uni.getStorageSync('userInfo').id,
							'fingerprint': that.fingerprint
						},
						success: (res) => {
							console.log(res,'识别ressssssss');
							if(+res.data.code === 200) {
								that.hasFind = true
								that.findImgUrl = res.data.data[0].filePath 
								that.$forceUpdate()
								uni.showToast({
									title:'识别成功',
									duration:1500,
									icon:'success'
								})
							}else {
								uni.showToast({
									title:'暂无匹配图片',
									duration:1500,
									icon:'error'
								})
							}
						}
					})
				}else {
					//请求修改个人信息接口
					uni.request({
						url: that.$serverUrl + 'upload',
						method: 'POST',
						header: {
							//token
							'token': uni.getStorageSync('token'),
							'content-type': 'application/json' //自定义请求头信息
						},
						data: {
							//只需传入图片信息与分类id
							'photoUrl': that.imgList[1],
							tagId: this.tagNameList[this.index].id,
							dateTime: `${currentYear}-0${currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`,
							userId: uni.getStorageSync('userInfo').id,
							title: this.title,
						},
						success: (res) => {
							if (res.data.code === 200) {
								uni.showToast({
									title: '发布成功',
									duration: 1500,
								});
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/tag/tag'
									});
								}, 1500)
							} else {
								uni.showToast({
								    title: '发布失败',
								    duration: 1500,
								    icon: 'none'
								});
							}
						},
						fail:(res) => {
							uni.showToast({
							    title: '发布失败',
							    duration: 1500,
							    icon: 'none'
							});
						}
					});
				}
			},
			//上传图片
			async changeAvatar(e) {
				if (this.imgList.length >= 2) return
				const fileList = [];
				try {
					const res = await uni.chooseImage({
						count: 1,
					});
					const arr = res[1]['tempFilePaths'].map((filePath) => {
						console.log('filePath', filePath)
						return new Promise(async (resolve, reject) => {
							uni.uploadFile({
								url: this.$serverUrl + 'uploadImg',
								name: 'file',
								header: {
									'token': uni.getStorageSync('token'),
								},
								filePath,
								success: (res) => {
								  this.imgList.push(JSON.parse(res.data).data.url)
								  this.fingerprint = JSON.parse(res.data).data.fingerprint
								  console.log(this.fingerprint,'fingerprintfingerprintfingerprint');
								},
								fail: (err) => {
								  uni.showToast({
									title: '上传失败',
									icon: 'none',
								  });
								},
							});
						});
					});
					const result = await Promise.all(arr);
					fileList.push(...result);
				} catch (error) {
					// if (error['errMsg'] !== 'chooseImage:fail cancel') showToast('上传失败，请重新上传！');
				}
				return fileList;
			},
			//清空所有参数
			clear() {
				var that = this
				that.photoUrl = ''
				that.fingerprint = ''
				that.filePath = ''
				that.tagId = 1
				that.index=0
				that.imgList = [
					"../../static/upload.png"
				]
				that.title=''
			},
			//获取所有分类
			getTagList() {
				var that = this
				uni.request({
					url: that.$serverUrl + 'tagList',
					method: 'GET',
					success: (res) => {
						var data = res.data
						uni.showLoading({
							title: data.msg
						});
						setTimeout(function() {
							if (data.code == 200) {
								//处理数据，构造两个一个只显示名称的数组
								that.tagList = data.data
								//深拷贝一下
								let tagListDrop = that.tagList
								tagListDrop.forEach(function(item) {
									that.tagNameList.push({
										id: item.id,
										name: item && item.name
									})
								})
							}
							uni.hideLoading();
						}, 500);
						console.log(data.data)
					}
				});
			},
			//改变picker
			bindPickerChange(e) {
				var that = this
				console.log(e)
				that.index = e.target.value
				//通过脚标找到对应的对象，取出id进行绑定
				that.tagId = that.tagList[that.index].id
			},
			
			closeCover() {
				this.hasFind = false
			}
		}
	}
</script>

<style>
	.imgflex {
		display: flex;
		    display: flex !important;
		    flex-direction: row;
			flex-wrap: wrap;
	}
	.imgflex image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 30rpx;
	}
	.findImg {
		position: absolute;
		top: 30%;
		left: 10%;
		z-index: 9;
	}
	.cover {
		background-color: rgba(0, 0, 0, 0.7);
		width: 100vw;
		height: 100%;
		position: absolute;
	}
	.btnClose {
		background: #fff;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		text-align: center;
		line-height: 20px;
		position: absolute;
		right: 10px;
		top: 5%;
	}
</style>
